<template>
  <div class="app-container">
    <el-row :gutter="15" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          plain
          size="mini"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>

      <el-form
        :inline="true"
        :model="formData"
        class="el-form-search"
        @submit.prevent
      >
        <!--设备选择-->
        <el-form-item class="el-form-search-item" label="设备" porp="device">
          <el-select
            v-model="formData.device"
            clearable
            filterable
            placeholder="请选择设备"
            @change="setChannelList"
          >
            <el-option
              v-for="device in deviceList"
              :key="device.zhGuid"
              :label="device.devName"
              :value="device.zhGuid"
            />
          </el-select>
        </el-form-item>
        <!--通道选择-->
        <el-form-item class="el-form-search-item" label="通道" porp="channel">
          <el-select
            v-model="formData.channel"
            clearable
            filterable
            placeholder="请选择设备类型"
          >
            <el-option
              v-for="channel in channelList"
              :key="channel.tdGuid"
              :label="channel.channelName"
              :value="channel.tdGuid"
            />
          </el-select>
        </el-form-item>
        <!--数据类型-->
        <el-form-item
          class="el-form-search-item"
          label="数据类型"
          porp="selectedTable"
        >
          <el-select
            v-model="formData.selectedTable"
            placeholder="请选择数据类型"
          >
            <el-option
              v-for="table in tables"
              :key="table.value"
              :label="table.label"
              :value="table.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="el-form-search-item" label="时间" porp="timeRange">
          <!-- 时间选择 -->
          <el-date-picker
            v-model="formData.timeRange"
            :picker-options="pickerOptions"
            end-placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            style="width: 400px"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <!-- 查询按钮 -->
        <el-button
          icon="el-icon-search"
          size="mini"
          type="primary"
          @click="getList"
          >搜索
        </el-button>
      </el-form>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      ref="elTable"
      :data="tableData"
      highlight-current-row
      height="calc(100vh - 200px)"
      border
      @row-dblclick="handleRowDbClick"
    >
      <el-table-column align="center" label="时间" prop="timedate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.timedate) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in fieldsList"
        :key="item.id"
        :label="item.fieldCnName"
        :prop="item.fieldName"
      >
      </el-table-column>
      <!--      <el-table-column fixed="right" label="操作" width="100">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button @click="handleClick(scope.row)" type="text" size="small"-->
      <!--          >查看-->
      <!--          </el-button-->
      <!--          >-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <!-- 分页控件 -->
    <pagination
      v-show="total > 0"
      :limit.sync="formData.pageSize"
      :page.sync="formData.pageNum"
      :total="total"
      @pagination="getList"
    />
    <el-dialog
      v-dialogDrag
      :before-close="handleClose"
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="dialogVisible"
      width="80%"
    >
      <!-- 在对话框中使用DataTable组件 -->
      <data-detail ref="dialogDataTable" :params="queryParams"></data-detail>

      <!--      <span slot="footer" class="dialog-footer">-->
      <!--        <el-button @click="dialogVisible = false">关闭</el-button>-->
      <!--        <el-button type="primary" @click="handleConfirm">确定</el-button>-->
      <!--      </span>-->
    </el-dialog>
  </div>
</template>

<script>
import { getBaseDataList } from "@/api/data_analysis/baseData.js";
import { getDeviceListFold } from "@/api/device/device";
import { getToken } from "@/utils/auth";
import { getSettingQueryFields } from "@/api/system/settingQUeryFields";
import { getTableDefinition } from "@/api/system/settingQUeryFields";
import DataDetail from "@/views/data_analysis/components/DataDetail/index.vue";
import filterConditions from "@/store/modules/filterConditions";

import * as XLSX from "xlsx";
import FileSaver from "file-saver";
import { getDeviceAndChannelByTdGuid } from "@/api/maintenance/channel";

export default {
  components: { DataDetail },
  data() {
    return {
      total: 0,
      tableHeight: window.innerHeight - 180,
      tables: [
        { value: "base", label: "原始数据" },
        { value: "avg", label: "平均值" },
        { value: "max", label: "最大值" },
        { value: "min", label: "最小值" },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      formData: {
        pageNum: 1,
        pageSize: 30,
        selectedTable: "base",
        timeRange: [
          new Date(2025, 0, 20), // 月份从0开始（0=1月）
          new Date(2025, 0, 22),
        ],
        device: "",
        channel: "",
        tableInfo: "db_basedata",
      },

      tableData: [],
      deviceList: [],
      channelList: [],
      fieldsList: [],
      tableInfoList: [],

      dialogVisible: false,
      title: "" || "详细数据",
      queryParams: {
        // 查询参数
      },
    };
  },
  watch: {
    formData: {
      handler(newForm, oldForm) {
        let obj = Object.assign({}, newForm);
        obj.datetime = newForm.timeRange;
        obj.device = newForm.device;
        obj.channel = newForm.channel;
        this.$store.commit("UPDATE_FILTER_CONDITIONS", obj);
        console.log(this.$store.state.filterConditions.filterConditions);
      },
      deep: true,
    },
  },
  created() {
    let obj = this.$store.state.filterConditions.filterConditions;
    if (obj) {
      if (obj.datetime) this.formData.timeRange = obj.datetime;
      this.formData.device = obj.device;
      this.formData.channel = obj.channel;
    }
    // this.$store.commit('UPDATE_FILTER_CONDITIONS',this.formData)
    // console.log(this.$store.state.filterConditions.filterConditions)
    if (
      this.$store.state.filterConditions.filterConditions.selectedTable !==
      undefined
    ) {
      //存数据
      console.log("缓存为空");
      console.log(this.$store.state.filterConditions.filterConditions);
    }

    console.log("获取字段表信息：");
    this.getFieldsAndTableList();
    this.getDeviceList();
    this.loadData();
  },
  methods: {
    getFieldsAndTableList(e) {
      this.getConfigKey("sys:fenxi:limit").then((response) => {
        getSettingQueryFields({
          tablePrefix: e || "db_basedata",
          isShow: 1,
          limit: response.msg,
        }).then((response) => {
          this.fieldsList = response.rows;
          console.log(this.fieldsList);
          this.getList();
        });
      });

      getTableDefinition().then((response) => {
        this.tableInfoList = response.rows;
        console.log(this.tableInfoList);
      });
    },
    getList() {
      // 格式化日期为后端期望的格式
      const dateRange = {
        startTime: "",
        endTime: "",
      };
      if (this.formData.timeRange && this.formData.timeRange.length > 1) {
        dateRange.startTime = this.parseTime(this.formData.timeRange[0]);
        dateRange.endTime = this.parseTime(this.formData.timeRange[1]);
      }
      getBaseDataList({
        pageNum: this.formData.pageNum,
        pageSize: this.formData.pageSize,
        tdGuid: this.formData.channel,
        tableName:
          this.formData.tableInfo +
          (this.formData.selectedTable === "base"
            ? ""
            : this.formData.selectedTable),
        fields: this.fieldsList.map((item) => item.fieldName),
        ...dateRange,
      })
        .then((res) => {
          console.log(res);
          this.tableData = res.rows;
          this.total = res.total;
          this.$refs.elTable.doLayout();
        })
        .catch((err) => {
          this.$message.error("数据加载失败");
        });
    },
    loadData() {
      if (
        !this.formData.selectedTable ||
        !this.formData.timeRange?.length === 2
      ) {
        this.$message.warning("请选择表和时间范围");
        return;
      }

      this.getList();
    },

    handleClick(row) {
      let suffix;
      if (this.formData.selectedTable !== "db_basedata") {
        suffix = this.formData.selectedTable.slice(-3);
      }
      //跳转到详细页面
      this.$router.push({
        path: "/data/data-detail",
        name: "dataDetail",
        params: {
          timedate: row.timedate,
          tableNameSuffix:
            this.formData.selectedTable === "base"
              ? ""
              : this.formData.selectedTable,
          tdGuid: row.tdGuid,
        },
      });
    },

    getDeviceList() {
      getDeviceListFold().then((res) => {
        console.log(res);
        this.deviceList = res.rows;
        this.channelList = [];
        if (this.formData.device !== null || this.formData.device !== "") {
          this.channelList = this.deviceList.filter((item) => {
            return item.zhGuid === this.formData.device;
          })[0].channelList;
        }
      });
    },
    setChannelList(selectedValue) {
      this.channelList = [];
      this.channelList = this.deviceList.filter((item) => {
        return item.zhGuid === selectedValue;
      })[0].channelList;
      this.formData.channel = this.channelList[0].tdGuid;
    },
    formatISODate(isoDateStr) {
      const date = new Date(isoDateStr);

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleRowDbClick(row, column, event) {
      console.log(row.tdGuid);

      getDeviceAndChannelByTdGuid(row.tdGuid).then((res) => {
        console.log(res);
        // this.formData.device = res.rows[0].zhGuid;
        // this.setChannelList(res.rows[0].zhGuid);
        this.title =
          res.data.deviceName +
          " · " +
          res.data.channelName +
          " · " +
          this.formatISODate(row.timedate);
        console.log(this.title);
      });

      this.queryParams = {
        timedate: row.timedate,
        tableNameSuffix:
          this.formData.selectedTable === "base"
            ? ""
            : this.formData.selectedTable,
        tdGuid: row.tdGuid,
      };
      this.openDialog();
    },
    // 打开对话框
    openDialog() {
      this.dialogVisible = true;
      // 如果需要在打开对话框时重新加载数据，可以添加以下代码
      this.$nextTick(() => {
        this.$refs.dialogDataTable.getList();
      });
    },
    // 对话框关闭前的回调
    handleClose(done) {
      // 可以在这里添加关闭前的确认逻辑
      done();
    },
    // 确认按钮点击事件
    handleConfirm() {
      // 可以获取子组件的数据进行处理
      const tableData = this.$refs.dialogDataTable.tableData;
      console.log("表格数据:", tableData);

      // 关闭对话框
      this.dialogVisible = false;
    },
    // 更新查询参数
    updateQueryParams(newParams) {
      this.queryParams = { ...this.queryParams, ...newParams };
      // 如果对话框已打开，刷新数据
      if (this.dialogVisible && this.$refs.dialogDataTable) {
        this.$refs.dialogDataTable.getList();
      }
    },
    handleExport() {
      // 格式化日期为后端期望的格式
      // const formatDate = (date) => {
      //   const d = new Date(date);
      //   const pad = (num) => (num < 10 ? "0" + num : num);

      //   return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(
      //     d.getDate()
      //   )} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
      // };

      getBaseDataList({
        tdGuid: this.formData.channel,
        tableName:
          this.formData.tableInfo +
          (this.formData.selectedTable === "base"
            ? ""
            : this.formData.selectedTable),
        fields: this.fieldsList.map((item) => item.fieldName),
        startTime: this.parseTime(this.formData.timeRange[0]),
        endTime: this.parseTime(this.formData.timeRange[1]),
      }).then((res) => {
        this.ExportExcel(res.rows);
      });
    },
    ExportExcel(ExportData) {
      const workbook = XLSX.utils.book_new();
      let arr3 = this.fieldsList.map((item) => {
        return item.fieldCnName;
      });
      let arr4 = this.fieldsList.map((item) => {
        return item.fieldName;
      });
      // 创建工作簿
      const headers = ["时间", ...arr3];
      const fields = ["timedate", ...arr4];
      // 定义自定义表头
      // const headers = ['日期', '姓名', '地址']; // 自定义表头
      // 定义表头对应的字段名
      // const fields = ['date', 'name', 'address'];
      // console.log(headers)
      // console.log(fields)

      // return

      // 准备数据（包括表头）
      const data = [headers];

      // 添加数据行
      ExportData.forEach((item) => {
        const row = [];
        fields.forEach((field) => {
          row.push(item[field]);
        });
        data.push(row);
      });
      console.log(data);

      // 将数据转换为工作表
      const worksheet = XLSX.utils.aoa_to_sheet(data);

      // 设置列宽
      const colWidth = [
        { wch: 15 }, // 日期列宽
      ];
      for (let i = 0; i++; i < this.fieldsList.length + 1) {
        colWidth.push({ wch: 10 });
      }

      worksheet["!cols"] = colWidth;

      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, "表格数据");

      // 生成Excel文件并下载
      const excelBuffer = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
        cellStyles: true,
      });
      const blob = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      FileSaver.saveAs(blob, "表格数据.xlsx");
    },
  },
};
</script>
